<template>
  <view class="container">
    <view class="header">
      <text @click="goBack" class="iconfont icon-back"></text>
      <text class="title">{{ taskTitle }}</text>
      <text @click="editTask" class="iconfont icon-edit"></text>
    </view>
    
    <view class="timer-container">
      <view class="time-display">
        <text class="time-number">{{ hours.toString().padStart(2, '0') }}</text>
        <text class="time-separator">:</text>
        <text class="time-number">{{ minutes.toString().padStart(2, '0') }}</text>
        <text class="time-separator">:</text>
        <text class="time-number">{{ seconds.toString().padStart(2, '0') }}</text>
      </view>
      
      <view class="task-info">
        <text class="task-desc">{{ taskDesc || '专注于当前任务' }}</text>
        <view class="task-tag" :style="{backgroundColor: getTagColor(taskTag)}">{{ getTagName(taskTag) }}</view>
      </view>
    </view>
    
    <view class="timer-controls">
      <view class="time-setting">
        <view class="time-unit" @click="adjustTime('hours', -1)">
          <text class="iconfont icon-minus"></text>
        </view>
        <view class="time-value">
          <text>{{ hours }}</text>
          <text class="unit-text">时</text>
        </view>
        <view class="time-unit" @click="adjustTime('hours', 1)">
          <text class="iconfont icon-plus"></text>
        </view>
        
        <view class="time-unit" @click="adjustTime('minutes', -1)">
          <text class="iconfont icon-minus"></text>
        </view>
        <view class="time-value">
          <text>{{ minutes }}</text>
          <text class="unit-text">分</text>
        </view>
        <view class="time-unit" @click="adjustTime('minutes', 1)">
          <text class="iconfont icon-plus"></text>
        </view>
        
        <view class="time-unit" @click="adjustTime('seconds', -1)">
          <text class="iconfont icon-minus"></text>
        </view>
        <view class="time-value">
          <text>{{ seconds }}</text>
          <text class="unit-text">秒</text>
        </view>
        <view class="time-unit" @click="adjustTime('seconds', 1)">
          <text class="iconfont icon-plus"></text>
        </view>
      </view>
      
      <view class="control-buttons">
        <view class="control-btn" @click="toggleFullScreen">
          <text class="iconfont icon-fullscreen"></text>
          <text>全屏</text>
        </view>
        <view class="control-btn" @click="toggleTimer">
          <text class="iconfont" :class="timerRunning ? 'icon-pause' : 'icon-play'"></text>
          <text>{{ timerRunning ? '暂停' : '开始' }}</text>
        </view>
        <view class="control-btn" @click="resetTimer">
          <text class="iconfont icon-reset"></text>
          <text>重置</text>
        </view>
      </view>
    </view>
    
    <view class="progress-container">
      <view class="progress-bar" :style="{width: progress + '%'}"></view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
import { getTask, updateTask, completeTask } from '@/utils/storage.js'
import { getSetting } from '@/utils/setting.js'

const taskId = ref('')
const taskTitle = ref('')
const taskDesc = ref('')
const taskTag = ref('')
const originalDuration = ref(0)
const remainingSeconds = ref(0)
const timerRunning = ref(false)
const timerInterval = ref(null)
const progress = ref(0)
const hours = ref(0)
const minutes = ref(0)
const seconds = ref(0)
const isDarkMode = ref(false)

onMounted(() => {
  const eventChannel = getCurrentPages()[getCurrentPages().length - 1].getOpenerEventChannel()
  eventChannel.on('acceptDataFromOpenerPage', function(data) {
    if (data.taskId) {
      taskId.value = data.taskId
      loadTask()
    }
  })
  
  const options = getCurrentPages()[getCurrentPages().length - 1].options
  if (options.id) {
    taskId.value = options.id
    loadTask()
  }
  
  loadSetting()
})

onUnmounted(() => {
  clearTimer()
})

const loadTask = async () => {
  if (!taskId.value) return
  
  const task = await getTask(taskId.value)
  if (task) {
    taskTitle.value = task.title
    taskDesc.value = task.description
    taskTag.value = task.tag
    originalDuration.value = task.duration || 0
    resetTimer()
  }
}

const loadSetting = async () => {
  const setting = await getSetting()
  isDarkMode.value = setting.darkMode || false
}

const toggleTimer = () => {
  if (timerRunning.value) {
    pauseTimer()
  } else {
    startTimer()
  }
}

const startTimer = () => {
  if (timerInterval.value) return
  
  timerRunning.value = true
  remainingSeconds.value = hours.value * 3600 + minutes.value * 60 + seconds.value
  
  timerInterval.value = setInterval(() => {
    remainingSeconds.value--
    
    if (remainingSeconds.value <= 0) {
      clearInterval(timerInterval.value)
      timerInterval.value = null
      timerRunning.value = false
      onTimerComplete()
    }
    
    updateTimeDisplay()
    updateProgress()
  }, 1000)
}

const pauseTimer = () => {
  if (timerInterval.value) {
    clearInterval(timerInterval.value)
    timerInterval.value = null
  }
  timerRunning.value = false
}

const resetTimer = () => {
  pauseTimer()
  
  if (originalDuration.value > 0) {
    hours.value = Math.floor(originalDuration.value / 3600)
    minutes.value = Math.floor((originalDuration.value % 3600) / 60)
    seconds.value = originalDuration.value % 60
  } else {
    hours.value = 0
    minutes.value = 25
    seconds.value = 0
  }
  
  remainingSeconds.value = hours.value * 3600 + minutes.value * 60 + seconds.value
  updateProgress()
}

const updateTimeDisplay = () => {
  hours.value = Math.floor(remainingSeconds.value / 3600)
  minutes.value = Math.floor((remainingSeconds.value % 3600) / 60)
  seconds.value = remainingSeconds.value % 60
}

const updateProgress = () => {
  const totalSeconds = originalDuration.value || (hours.value * 3600 + minutes.value * 60 + seconds.value)
  if (totalSeconds <= 0) {
    progress.value = 0
    return
  }
  
  const elapsedSeconds = totalSeconds - remainingSeconds.value
  progress.value = (elapsedSeconds / totalSeconds) * 100
}

const adjustTime = (unit, amount) => {
  if (timerRunning.value) return
  
  if (unit === 'hours') {
    hours.value = Math.max(0, Math.min(99, hours.value + amount))
  } else if (unit === 'minutes') {
    minutes.value = Math.max(0, Math.min(59, minutes.value + amount))
  } else if (unit === 'seconds') {
    seconds.value = Math.max(0, Math.min(59, seconds.value + amount))
  }
  
  remainingSeconds.value = hours.value * 3600 + minutes.value * 60 + seconds.value
  updateProgress()
}

const onTimerComplete = async () => {
  // 保存任务完成状态
  if (taskId.value) {
    await completeTask(taskId.value)
  }
  
  // 播放提醒
  const setting = await getSetting()
  if (setting.soundReminder) {
    playSound(setting.ringtone || 'default')
  }
  
  if (setting.vibrateReminder) {
    uni.vibrateLong()
  }
  
  // 显示通知
  if (setting.notificationReminder) {
    showNotification('专注时间结束', '任务已完成')
  }
  
  // 提示用户
  uni.showToast({
    title: '时间到！',
    icon: 'none'
  })
}

const playSound = (ringtone) => {
  // 播放声音逻辑
  console.log('播放声音:', ringtone)
}

const showNotification = (title, content) => {
  // 显示通知逻辑
  console.log('显示通知:', title, content)
}

const toggleFullScreen = () => {
  uni.navigateTo({
    url: `/pages/fullscreen/fullscreen?taskId=${taskId.value}&hours=${hours.value}&minutes=${minutes.value}&seconds=${seconds.value}`
  })
}

const goBack = () => {
  pauseTimer()
  uni.navigateBack()
}

const editTask = () => {
  pauseTimer()
  uni.navigateTo({
    url: `/pages/taskEdit/taskEdit?id=${taskId.value}`
  })
}

const getTagColor = (tag) => {
  const colors = {
    work: '#165DFF',
    study: '#36B37E',
    life: '#FF5630'
  }
  return colors[tag] || '#165DFF'
}

const getTagName = (tag) => {
  const names = {
    work: '工作',
    study: '学习',
    life: '生活'
  }
  return names[tag] || '其他'
}

const clearTimer = () => {
  if (timerInterval.value) {
    clearInterval(timerInterval.value)
    timerInterval.value = null
  }
}

watch([hours, minutes, seconds], () => {
  if (!timerRunning.value) {
    remainingSeconds.value = hours.value * 3600 + minutes.value * 60 + seconds.value
    updateProgress()
  }
})
</script>

<style scoped>
.container {
  padding: 20rpx;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f7f7;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
}

.timer-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
}

.time-display {
  font-size: 120rpx;
  font-weight: bold;
  color: #165DFF;
  display: flex;
  align-items: center;
}

.time-number {
  min-width: 180rpx;
  text-align: center;
}

.time-separator {
  padding: 0 20rpx;
}

.task-info {
  margin-top: 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.task-desc {
  font-size: 36rpx;
  text-align: center;
  max-width: 600rpx;
  margin-bottom: 20rpx;
}

.task-tag {
  padding: 10rpx 20rpx;
  border-radius: 16rpx;
  font-size: 28rpx;
  color: #fff;
}

.timer-controls {
  margin-bottom: 40rpx;
}

.time-setting {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 40rpx;
}

.time-unit {
  width: 80rpx;
  height: 80rpx;
  background-color: #e6e6e6;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 36rpx;
}

.time-value {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 30rpx;
}

.time-value text:first-child {
  font-size: 48rpx;
  font-weight: bold;
}

.unit-text {
  font-size: 24rpx;
  color: #666;
}

.control-buttons {
  display: flex;
  justify-content: center;
  gap: 40rpx;
}

.control-btn {
  width: 160rpx;
  height: 160rpx;
  background-color: #165DFF;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #fff;
}

.control-btn text:first-child {
  font-size: 48rpx;
}

.control-btn text:last-child {
  font-size: 28rpx;
  margin-top: 10rpx;
}

.progress-container {
  height: 12rpx;
  background-color: #e6e6e6;
  border-radius: 6rpx;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  background-color: #165DFF;
  transition: width 0.3s;
}

/* 暗黑模式样式 */
.container.dark {
  background-color: #1c1c1e;
  color: #fff;
}

.container.dark .time-setting .time-unit {
  background-color: #3a3a3c;
}

.container.dark .progress-container {
  background-color: #3a3a3c;
}
</style>  